/* @flow */
/* globals MutationObserver */

/* 
  $nextTick的应用场景：我们需要这次数据更新对应的DOM更新完成后走某些事情的时候 才会使用

  每当用户调用$nextTick的时候 都是项callbacks这个数组中调价回调函数
  第一次nextTick执行 是vue内部调用的  会把pending变成true,
  并且启动一个异步函数（timerFunc）去执行 flushCallbacks
  flushCallbacks就是挨个执行callbacks中的回调函数，并且清空callbacks
  第一次nextTick执行完成之后，后续的nextTick执行 就只会向callbacks中添加回调函数
  不会再去启动异步函数了(由pending这个变量去决定了)


  这个异步函数 原则上是能用微任务就是用微任务 没办法的话采取使用了宏任务


*/

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'

export let isUsingMicroTask = false;// 判断或者记录是否使用微任务

const callbacks = [] // 事件池 用来存储各种事件的(就是nextTick传递的哪些回调函数)
let pending = false  // 用来记录是否处在渲染中的一个状态

function flushCallbacks() {
  //  清空事件池
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
// let timerFunc

// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
// if (typeof Promise !== 'undefined' && isNative(Promise)) {
//   const p = Promise.resolve()
//   timerFunc = () => {
//     p.then(flushCallbacks)
//     // In problematic UIWebViews, Promise.then doesn't completely break, but
//     // it can get stuck in a weird state where callbacks are pushed into the
//     // microtask queue but the queue isn't being flushed, until the browser
//     // needs to do some other work, e.g. handle a timer. Therefore we can
//     // "force" the microtask queue to be flushed by adding an empty timer.
//     if (isIOS) setTimeout(noop)
//   }
//   isUsingMicroTask = true
// } else if (!isIE && typeof MutationObserver !== 'undefined' && (
//   isNative(MutationObserver) ||
//   // PhantomJS and iOS 7.x
//   MutationObserver.toString() === '[object MutationObserverConstructor]'
// )) {
//   // Use MutationObserver where native Promise is not available,
//   // e.g. PhantomJS, iOS7, Android 4.4
//   // (#6466 MutationObserver is unreliable in IE11)
//   let counter = 1
//   const observer = new MutationObserver(flushCallbacks)
//   const textNode = document.createTextNode(String(counter))
//   observer.observe(textNode, {
//     characterData: true
//   })
//   timerFunc = () => {
//     counter = (counter + 1) % 2
//     textNode.data = String(counter)
//   }
//   isUsingMicroTask = true
// } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
//   // Fallback to setImmediate.
//   // Technically it leverages the (macro) task queue,
//   // but it is still a better choice than setTimeout.
//   timerFunc = () => {
//     setImmediate(flushCallbacks)
//   }
// } else {
//   // Fallback to setTimeout.
//   timerFunc = () => {
//     setTimeout(flushCallbacks, 0)
//   }
// }

let timerFunc = () => { setTimeout(flushCallbacks, 0) }

export function nextTick(cb, ctx) {
  let _resolve
  callbacks.push(() => {
    if (cb) {
      try {
        cb.call(ctx)
      } catch (e) {
        handleError(e, ctx, 'nextTick')
      }
    } else if (_resolve) {
      _resolve(ctx)
    }
  })
  if (!pending) {
    pending = true
    timerFunc()
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}
